package com.ubxtech.core.utils;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author Victor.Xiao
 * @since 2022-01-14 11:44
 **/
public class JsonUtils {
    private static Pattern linePattern = Pattern.compile("_(\\w)");
    private static Pattern humpPattern = Pattern.compile("[A-Z]");

    /**
     *
     * 驼峰转下划线,最后转为大写
     * userName  ---->  user_name
     * user_name  ---->  user_name
     * @author Victor.Xiao
     * @since 2022-01-14 12:37
     * @param str str
     * @return java.lang.String
    */
    public static String toUnderlineCase(String str) {
        Matcher matcher = humpPattern.matcher(str);
        StringBuffer sb = new StringBuffer();
        while (matcher.find()) {
            matcher.appendReplacement(sb, "_" + matcher.group(0).toUpperCase());
        }
        matcher.appendTail(sb);
        return sb.toString().toLowerCase();
    }

    /**
     * 下划线转驼峰,正常输出
     * user_name  ---->  userName
     * userName   --->  userName
     * @author Victor.Xiao
     * @since 2022-01-14 12:37
     * @param str str
     * @return java.lang.String
    */
    public static String toCamelCase(String str) {
        Matcher matcher = linePattern.matcher(str);
        StringBuffer sb = new StringBuffer();
        while (matcher.find()) {
            matcher.appendReplacement(sb, matcher.group(1).toUpperCase());
        }
        matcher.appendTail(sb);
        return sb.toString();
    }

    public static void main(String[] args) {
        System.out.println(JsonUtils.toCamelCase("user_name"));
        System.out.println(JsonUtils.toUnderlineCase("userName"));
    }
}
